package cn.tedu.order.tx;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Component
public class OrderTccActionImpl implements OrderTccAction {
    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @Override
    public synchronized boolean prepare(BusinessActionContext ctx, Long orderId, Long userId, Long productId, Integer count, BigDecimal money) {
        //插入冻结订单
        orderMapper.createFrozen(new Order(
                orderId,userId,productId,count,money,0
        ));
        //第一阶段成功，添加标记
        ResultHolder.setResult(OrderTccAction.class, ctx.getXid(), "p");
        return true;
    }
    @Transactional
    @Override
    public synchronized boolean commit(BusinessActionContext ctx) {
        //判断第一阶段的成功标记是否存在
        //  - 第一阶段没有成功
        //  - 第二阶段已经执行过一次，标记已经被删除
        if (ResultHolder.getResult(OrderTccAction.class, ctx.getXid()) == null) {
            return true;
        }

        /*
        从第一阶段向第二阶段传递的 Context 对象，
        先转成 json，整数类型会丢失，
        转回成 Context 对象时，整数可能是 Integer，也可能是Long
         */
        Long orderId = Long.valueOf(
                ctx.getActionContext("orderId").toString());

        // 冻结状态改成正常状态
        orderMapper.updateStatus(orderId, 1);

        // 第二阶段执行完成后，删除标记
        ResultHolder.removeResult(OrderTccAction.class, ctx.getXid());
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean rollback(BusinessActionContext ctx) {
        if (ResultHolder.getResult(OrderTccAction.class, ctx.getXid()) == null) {
            return true;
        }
        Long orderId = Long.valueOf(
                ctx.getActionContext("orderId").toString());

        // 删除订单
        orderMapper.deleteByOrderId(orderId);
        ResultHolder.removeResult(OrderTccAction.class, ctx.getXid());
        return true;
    }
}
